package com.ja.openchat.views;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.OnContactChatInfoListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import androidx.annotation.NonNull;

public class ChatUserDialog extends BaseBottomDialog{

    private final UserInfo user;
    private final OnItemClickListner listner;
    private UserAvatarView avatarView;
    private boolean toShowInvidePath;//邀请来源
    private boolean blockContact;//是否显示用户账号

    private ChatInfo mChatInfo;
    private OrgUserInfo orgUserInfo;

    private LinearLayout addLayout;


    public ChatUserDialog(@NonNull Context context,UserInfo user, boolean blockContact, OnItemClickListner listner) {
        super(context);
        this.user = user;
        this.blockContact = blockContact;
        this.listner = listner;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_chat_user_view;
    }


    @Override
    protected void onCreate() {
        super.onCreate();
        addLayout = findViewById(R.id.addLayout);
        avatarView = findViewById(R.id.header_image_view);
        TextView headerName = findViewById(R.id.user_name);
        TextView userNum = findViewById(R.id.tv_user_num);
        LinearLayout llNickName = findViewById(R.id.ll_nickname);

        if(user != null){
            requestOrgUserInfo();
            avatarView.showUser(user);
//            String name = user.displayName();
//            if(!TextUtils.isEmpty(name)){
//                headerName.setText(user.first_name);
//            }else {
//                headerName.setText("");
//            }
            headerName.setText(user.displayName());


            if (blockContact) {
                userNum.setText("FISE号：******");
            } else {
                if (!StringUtils.isEmpty(user.username)) {
                    userNum.setText("FISE号："+user.username);
                } else {
                    userNum.setText("FISE号：");
                }
            }

        }
        findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        llNickName.setOnClickListener(v -> {
            if(mChatInfo == null){
                ToastUtils.showShort("数据异常，请重新打开界面");
                return;
            }
            new XPopup.Builder(getContext())
                    .hasShadowBg(true)
                    .isDestroyOnDismiss(true)
                    .dismissOnTouchOutside(true)
                    .moveUpToKeyboard(false)
                    .borderRadius(10)
                    .atView(llNickName)
                    .asCustom(new ChatUserModifyDialog(getContext(), user,mChatInfo, new ChatUserModifyDialog.OnItemClickListner() {
                        @Override
                        public void clickSave(String name) {
                            headerName.setText(name);
                            user.first_name = name;
                        }
                    })).show();
        });

        findViewById(R.id.iv_menu).setOnClickListener(v -> {
            //菜单
            new XPopup.Builder(getContext())
                    .hasShadowBg(true)
                    .isDestroyOnDismiss(true)
                    .dismissOnTouchOutside(true)
                    .moveUpToKeyboard(false)
                    .borderRadius(10)
                    .atView(llNickName)
                    .asCustom(new ChatUserMenuDialog(getContext(), user,blockContact,mChatInfo, new ChatUserMenuDialog.OnItemClickListner() {

                        @Override
                        public void clickPostion(int position, ChatInfo postion) {
                            dismiss();
                        }
                    })).show();
        });

        findViewById(R.id.ll_send_message).setOnClickListener(v -> {
            //发送消息
            if(!canSendMsg()){
                ToastUtils.showShort(getContext().getString(R.string.other_not_friend_first_add));
                return;
            }
            if (user != null) {
                TelegramManager.getTelegramManager().createPrivateChat(getContext(), user.id, new TgResultBlock<ChatInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                        if (obj != null) {
                            ChatActivity.startActivity((Activity) getContext(), obj);
                            dismiss();
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                    }
                });
            }else {
                ToastUtils.showShort("数据异常");
            }
        });
        findViewById(R.id.ll_video_voice).setOnClickListener(v -> {
            //音视频通话
            new XPopup.Builder(getContext())
                    .hasShadowBg(true)
                    .isDestroyOnDismiss(true)
                    .dismissOnTouchOutside(true)
                    .moveUpToKeyboard(false)
                    .borderRadius(10)
                    .atView(llNickName)
                    .asCustom(new ChatUserVideoMenuDialog(getContext(), user, new ChatUserVideoMenuDialog.OnItemClickListner() {

                        @Override
                        public void clickPostion(int position, ChatInfo postion) {

                        }
                    })).show();
        });

        addLayout.setOnClickListener(v -> {
            if (user != null) {
                clickAdd();
            }
        });
//
        requestChatInfo(new OnContactChatInfoListener() {
            @Override
            public void onResult(ChatInfo chatInfo) {
                mChatInfo = chatInfo;
            }
        });

        setUI();

    }

    private boolean canSendMsg() {
        if (user != null) {
            return user.canSendMsg();
        }
        return false;
    }

    private void requestChatInfo(OnContactChatInfoListener listener){
        ChatInfo chatInfo = null;
        if(chatInfo!=null){
            listener.onResult(chatInfo);
        }else if(user!=null){
            TelegramManager.getTelegramManager().createPrivateChat(getContext(), user.id, new TgResultBlock<ChatInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                    if (obj != null) {
                        listener.onResult(obj);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }else{
            listener.onResult(chatInfo);
        }
    }

    private void setUI(){
        //操作菜单
        if (blockContact) {
            addLayout.setVisibility(View.GONE);
//            binding.pingbiLayout.setVisibility(View.GONE);
//            binding.sendMsgLayout.setVisibility(View.GONE);
        } else {
            boolean isShowUserNameView = false;
            addLayout.setVisibility(View.VISIBLE);
//            binding.pingbiLayout.setVisibility(View.VISIBLE);
//            binding.sendMsgLayout.setVisibility(View.VISIBLE);
            if (user.is_contact) {
                isShowUserNameView = true;
//                binding.pingbiLayout.setVisibility(View.GONE);
                addLayout.setVisibility(View.GONE);
            } else {
                if (!canAddFriend()) {
                    isShowUserNameView = true;
//                    binding.pingbiLayout.setVisibility(View.GONE);
                    addLayout.setVisibility(View.GONE);
                }
            }
        }

        if(addLayout.getVisibility() == View.VISIBLE){
            findViewById(R.id.iv_menu).setVisibility(GONE);
            findViewById(R.id.tv_user_num).setVisibility(VISIBLE);
            findViewById(R.id.ll_nickname).setVisibility(GONE);
            findViewById(R.id.line).setVisibility(GONE);
            findViewById(R.id.ll_bottom).setVisibility(GONE);
        }else {
            findViewById(R.id.iv_menu).setVisibility(VISIBLE);
            findViewById(R.id.tv_user_num).setVisibility(VISIBLE);
            findViewById(R.id.ll_nickname).setVisibility(VISIBLE);
            findViewById(R.id.line).setVisibility(VISIBLE);
            findViewById(R.id.ll_bottom).setVisibility(VISIBLE);
        }

    }


    private OrgUserInfo loginOrgUserInfo;
    private void getLoginOrgUserInfo(){
        TelegramManager.getTelegramManager().requestOrgContactInfo(getContext(), UserInfo.getUserInfo().id, new TgResultBlock<OrgUserInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                loginOrgUserInfo = obj;
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }
    /**
     * 请求原始联系人信息
     */
    public void requestOrgUserInfo() {
        if (user != null) {
            TelegramManager.getTelegramManager().requestOrgContactInfo(getContext(), user.id, new TgResultBlock<OrgUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                    if (obj != null) {
                        orgUserInfo = obj;
                        String userName = orgUserInfo.displayName();
                        String nickName = user.displayName();
                        TextView tvNickName = findViewById(R.id.tv_nickname);
                        if(!TextUtils.equals(userName,nickName)){
                            tvNickName.setVisibility(VISIBLE);
                            tvNickName.setText("昵称："+nickName);
                        }else {
                            tvNickName.setVisibility(GONE);
                        }
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }
    }
    private boolean canAddFriend() {
        if(loginOrgUserInfo!=null&&loginOrgUserInfo.isInternal){
            return true;
        }
        AppConfigInfo info = AppConfigInfo.getAppConfigInfo();
        if (info != null) {
            if (info.onlyWhiteAddFriend) {
                return orgUserInfo != null ? orgUserInfo.isInternal : false;
            }
        }
        return true;
    }

    private void clickAdd() {//添加好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getContext().getString(R.string.want_add_somebody_as_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doAddContact();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void doAddContact() {
        showProgress();
        TelegramManager.getTelegramManager().addContact(getContext(), user, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getContext().getString(R.string.request_error) + obj.errString);
                } else {
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(String.format(getContext().getString(R.string.somebody_added_friends), user.displayName()));
                    TelegramManager.getTelegramManager().sendBeFriendMessage(getContext(), user.id, new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                            dismiss();
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                        }
                    });
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getContext().getString(R.string.request_error));
            }
        });
    }


    @Override
    protected void onShow() {
        super.onShow();
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
    }

    @Override
    protected int getMaxHeight() {
        return (int) (XPopupUtils.getAppHeight(getContext()) * 0.98f);
    }


    public interface OnItemClickListner {
        void clickPostion(int position,ChatInfo postion);
    }

}
